package com.leyou.item.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper , SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService specParamService;

    @Override

    public List<SpecGroupDTO> queryParamById(Long categoryId) {
        //查询分类规格组
        List<SpecGroup> groupIds = query().eq("category_id", categoryId).list();
        //将查询到的数据放到输出数据中
        List<SpecGroupDTO> groupDTOList = SpecGroupDTO.convertEntityList(groupIds);
        //判断分类规格组中param是否有信息
        if (CollectionUtils.isEmpty(groupDTOList)){
           //没有直接返回
            return groupDTOList;
        }
        //查询所有的param，
        List<SpecParamDTO> paramAll = specParamService.queryParam(categoryId, null, null);
        //将所有的param添加到map中
        //stream流简化版
        Map<Long, List<SpecParamDTO>> map = paramAll.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

            /*Map<Long , List<SpecParamDTO>> map = new HashMap<>();
            //将所有的param添加到map中
            for (SpecParamDTO paramDTO : paramAll){
            //得到param的规格组
            Long groupId = paramDTO.getGroupId();
            //判断groupId是否存在
            if (!map.containsKey(groupId)){
                //不存在为空
                map.put(groupId,new ArrayList<>());
            }
            //存在拿出来将param放进去
            map.get(groupId).add(paramDTO);
        }*/

        /*//查询每个组的规格参数
        for (SpecGroupDTO specGroupDTO : specGroupDTOList){
            //获取groupId
            Long id = specGroupDTO.getId();
            //根据groupId查询param信息
            List<SpecParamDTO> paramDTOList = specParamService.queryParam(null, id, null);
            specGroupDTO.setParams(paramDTOList);
        }*/

        //查询每个组的规格参数
        for (SpecGroupDTO groupDTO : groupDTOList){
            //获取groupId
            Long groupId = groupDTO.getId();
            //根据groupId查询所有的param
            List<SpecParamDTO> paramList = map.get(groupId);
            //将查询到的param放到实现类中
            groupDTO.setParams(paramList);
        }
        //返回数组信息
        return groupDTOList ;
    }
}
